package com.project.card.ui;

import static com.project.card.util.UrlUtil.SERVER_URL;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;

import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.project.card.BusinessActivity;
import com.project.card.LoginActivity;
import com.project.card.MainActivity;
import com.project.card.R;

import org.w3c.dom.Text;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ProfileFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ProfileFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    public static final ObjectMapper JSONMAPPER = new ObjectMapper()
            .enable(JsonParser.Feature.IGNORE_UNDEFINED)
            .enable(JsonParser.Feature.ALLOW_COMMENTS)
            .enable(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES)
            .enable(JsonParser.Feature.ALLOW_SINGLE_QUOTES)
            .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

    private LinearLayout info;
    private LinearLayout question;
    private LinearLayout customer;
    private LinearLayout score;
    private Dialog dialog;
    
    private TextView textName;
    private TextView textCode;
    private Button btnExit;
    
    private SharedPreferences sp;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public ProfileFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment ProfileFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static ProfileFragment newInstance(String param1, String param2) {
        ProfileFragment fragment = new ProfileFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_profile, container, false);
        info = view.findViewById(R.id.profile_ll_inf);
        textName = view.findViewById(R.id.profile_name);
        textCode = view.findViewById(R.id.profile_code);
        score = view.findViewById(R.id.profile_item_B);
        question = view.findViewById(R.id.profile_item_C);
        customer = view.findViewById(R.id.profile_item_D);
        btnExit = view.findViewById(R.id.profile_exit);
        
        sp = getActivity().getSharedPreferences("current_user",Context.MODE_PRIVATE);
        boolean isLogin = sp.getBoolean("login",false);
        if(isLogin){
            textName.setText(sp.getString("name","未登录状态"));
            textCode.setText(sp.getString("code","未登录状态"));
            OkHttpClient client = new OkHttpClient();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try{
                        FormBody.Builder params = new FormBody.Builder();
                        params.add("phone",sp.getString("phone",""));
                        Request request = new Request.Builder()
                                .url(SERVER_URL+"user/findp")
                                .post(params.build())
                                .build();
                        Response response = client.newCall(request).execute();
                        String responseData = response.body().string();
                        JsonNode nodeUser =JSONMAPPER.readTree(responseData);
                        SharedPreferences.Editor editor  = sp.edit();
                        editor.putString("commentCode",nodeUser.get("data").get("commentCode").asText());
                        editor.commit();
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }).start();
        }
        info.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!sp.getBoolean("login",false)){
                    Intent intent = new Intent(getContext(), LoginActivity.class);
                    startActivity(intent);
                }
            }
        });
        score.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                        .setTitle("个人推荐码")
                        .setMessage("推荐码为"+sp.getString("commentCode","null"))
                        .setPositiveButton("确定",new DialogInterface.OnClickListener(){
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                            }
                        }).create();
                alertDialog.show();
            }
        });
        question.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showQuestion("question.txt");
            }
        });
        customer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(ActivityCompat.checkSelfPermission(getActivity(),Manifest.permission.CALL_PHONE )!=
                        PackageManager.PERMISSION_GRANTED ){
                    ActivityCompat.requestPermissions(getActivity(),new String[]{Manifest.permission.CALL_PHONE},1);
                }else {
                    Intent  intentPhone = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"+"99999999"));
                    startActivity(intentPhone);
                }
            }
        });
        
        btnExit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SharedPreferences.Editor editor = sp.edit();
                editor.clear();
                editor.commit();

            }
        });
        
        return view;
    }

    public void showQuestion(String questionFileName){
        String str = initAssets(questionFileName);
        final View inflate = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_question_show,null);
        TextView content = (TextView) inflate.findViewById(R.id.question_tv_content);
        content.setText(str);
        Button btnConfirm = inflate.findViewById(R.id.question_btn_confirm);
        btnConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });

        dialog = new AlertDialog.Builder(getActivity()).setView(inflate).show();

        DisplayMetrics dm = getResources().getDisplayMetrics();
        final WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
        params.width = dm.widthPixels*4/5;
        params.height = dm.heightPixels/2;
        dialog.setCancelable(false);
        dialog.getWindow().setAttributes(params);
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
    }

    public String initAssets(String fileName){
        String str=null;
        try{
            InputStream inputStream = getActivity().getAssets().open(fileName);
            str=getString(inputStream);
        }catch (IOException ioException){
            ioException.printStackTrace();
        }
        return str;
    }

    public static String getString(InputStream inputStream){
        InputStreamReader inputStreamReader = null;
        try{
            inputStreamReader = new InputStreamReader(inputStream,"UTF-8");
        }catch (UnsupportedEncodingException unsupportedEncodingException){
            unsupportedEncodingException.printStackTrace();
        }
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        StringBuffer sb = new StringBuffer("");
        String line;
        try{
            while((line = bufferedReader.readLine())!=null){
                sb.append(line);
                sb.append("\n");
            }
        }catch (IOException ioException){
            ioException.printStackTrace();
        }
        return sb.toString();
    }
}